package com.suyang.syt.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.dao.interfaces.UserDao;
import com.suyang.syt.dao.interfaces.UserGroupDao;
import com.suyang.syt.dao.interfaces.UserRoleDao;
import com.suyang.syt.model.User;
import com.suyang.syt.model.UserGroup;
import com.suyang.syt.model.UserRole;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.Captcha;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.model.dto.UserDTO;
import com.suyang.syt.service.interfaces.UserService;
import com.suyang.syt.util.AppUtil;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.Md5Util;
import com.suyang.syt.util.PinyinUtil;
import com.suyang.syt.util.StringUtil;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserGroupDao userGroupDao;
	@Autowired
	private UserRoleDao userRoleDao;

	@Override
	public AjaxObj updateRegist(String username, String password) throws Exception {
		if (username != null && !username.trim().equals("")) {
			boolean isMobileNo = StringUtil.isMobileNo(username);
			// 验证是否是手机号
			if (!isMobileNo) {
				return new AjaxObj(0, "该用户名不是手机号,请重新输入.");
			}
			if (userDao.countUsername(username) > 0) {
				return new AjaxObj(0, "该帐号已注册!");
			}
			// 添加用户
			User user = new User();
			user.setUsername(username);
			user.setPassword(Md5Util.md5(username, password));
			userDao.add(user);
			userGroupDao.add(new UserGroup(user.getId(), 2));
			userRoleDao.add(new UserRole(user.getId(), 2));
			return new AjaxObj(1, "注册成功");
		}

		return new AjaxObj(0, "注册失败");
	}

	/**
	 * 测试手机短信验证码
	 */
	@Override
	public AjaxObj updateRegistCheckCode(String username) throws Exception {
		if (userDao.countUsername(username) > 0) {
			return new AjaxObj(0, "该帐号已注册!");
		}
		Captcha c = Captcha.getInstance();
		return new AjaxObj(1, c.generateCheckcode());
	}

	@Override
	public AjaxObj add(UserDTO userDTO) throws Exception {
		if (userDTO != null && EmptyUtil.isNotEmpty(userDTO.getPassword()) && EmptyUtil.isNotEmpty(userDTO.getUsername())) {
			// 1、验证用户名唯一
			if (userDao.countUsername(userDTO.getUsername()) > 0) {
				return new AjaxObj(0, "已经存在该用户名，请重新添加！");
			}
			// 2、验证邮箱唯一
			if (userDao.countEmail(userDTO.getEmail()) > 0) {
				return new AjaxObj(0, "已经存在该邮箱，请重新添加！");
			}
			// 3、验证手机号唯一
			if (userDao.countPhone(userDTO.getPhone()) > 0) {
				return new AjaxObj(0, "已经存在该手机号，请重新添加！");
			}
			// 4、添加用户
			User user = new User();
			user.setCreateName(userDTO.getCreateName());
			user.setCreateTime(userDTO.getCreateTime());
			user.setEmail(userDTO.getEmail());
			user.setIcon(AppUtil.getLogo(userDTO.getIcon(), 5));
			user.setJianpin(PinyinUtil.strFirst2Pinyin(userDTO.getUsername()).toUpperCase());
			user.setQuanpin(PinyinUtil.str2Pinyin(userDTO.getUsername(), null));
			user.setNickname(userDTO.getNickname());
			user.setOrderIndex(userDTO.getOrderIndex());
			user.setPassword(Md5Util.md5(userDTO.getUsername(), userDTO.getPassword()));
			user.setPhone(userDTO.getPhone());
			user.setUsername(userDTO.getUsername());
			userDao.add(user);
			return new AjaxObj(1, "增加成功！");
		}
		return new AjaxObj(0, "增加失败！");
	}

	@Override
	public AjaxObj deletes(String ids) throws Exception {
		if (EmptyUtil.isNotEmpty(ids)) {
			// 1.批量删除用户管理的组对象
			userGroupDao.deleteUserGroups(ids);
			// 2.批量删除用户管理的角色对象
			userRoleDao.deleteUserRoles(ids);
			// 3.批量删除用户对象
			userDao.deletes(ids);
			return new AjaxObj(1, "删除用户成功！");
		} else {
			return new AjaxObj(0, "请选择要删除的记录！");
		}
	}

	@Override
	public AjaxObj update(UserDTO userDTO) throws Exception {
		if (userDTO != null && EmptyUtil.isNotEmpty(userDTO.getNickname()) && EmptyUtil.isNotEmpty(userDTO.getUsername())) {
			User user = userDao.load(userDTO.getId());
			if (user != null) {
				// 1、验证用户名唯一
				if (!userDTO.getUsername().equals(user.getUsername()) && userDao.countUsername(userDTO.getUsername()) > 0) {
					return new AjaxObj(0, "已经存在该用户名，不能更新！");
				}
				// 2、验证邮箱唯一
				if (!userDTO.getEmail().equals(user.getEmail()) && userDao.countEmail(userDTO.getEmail()) > 0) {
					return new AjaxObj(0, "已经存在该邮箱，不能更新！");
				}
				if (!userDTO.getPhone().equals(user.getPhone()) && userDao.countPhone(userDTO.getPhone()) > 0) {
					return new AjaxObj(0, "已经存在该手机号，不能更新！");
				}
				// 3、如果没有改密码则不执行，否则密码加密
				if (userDTO.getPassword() != null && !userDTO.getPassword().equals(user.getPassword())) {
					userDTO.setPassword(Md5Util.md5(userDTO.getUsername(), userDTO.getPassword()));
				}
				// 4、更新用户
				user.setModifyName(userDTO.getModifyName());
				user.setModifyTime(userDTO.getModifyTime());
				user.setEmail(userDTO.getEmail());
				user.setIcon(AppUtil.getLogo(userDTO.getIcon(), 5));
				user.setNickname(userDTO.getNickname());
				user.setPassword(userDTO.getPassword());
				user.setStatus(userDTO.getStatus());
				user.setUsername(userDTO.getUsername());
				user.setPhone(userDTO.getPhone());
				userDao.update(user);
				return new AjaxObj(1, "更新成功！");
			}
		}
		return new AjaxObj(0, "更新失败！");
	}

	@Override
	public PagerEasyUI<UserDTO> listByEasyUI(int page, int rows, String sort, String order, User user, String createDate1, String createDate2) throws Exception {
		// 1、拼接查询语句
		StringBuilder hql = new StringBuilder(" from User u where 1=1");
		if (EmptyUtil.isNotEmpty(createDate1)) {
			hql.append(" and u.createTime >= '").append(createDate1).append("' ");
		}
		if (EmptyUtil.isNotEmpty(createDate2)) {
			hql.append(" and u.createTime <= '").append(createDate2).append("' ");
		}
		if (user != null && EmptyUtil.isNotEmpty(user.getEmail())) {
			hql.append(" and u.email like '%").append(user.getEmail()).append("%' ");
		}
		if (user != null && EmptyUtil.isNotEmpty(user.getPhone())) {
			hql.append(" and u.phone like '%").append(user.getPhone()).append("%' ");
		}
		if (user != null && EmptyUtil.isNotEmpty(user.getNickname())) {
			hql.append(" and u.nickname like '%").append(user.getNickname()).append("%' ");
		}
		if (user != null && EmptyUtil.isNotEmpty(user.getUsername())) {
			hql.append(" and u.username like '%").append(user.getUsername()).append("%' ");
		}
		if (user != null && user.getStatus() != 0) {
			hql.append(" and u.status = ").append(user.getStatus());
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by u.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<UserDTO> easyUIPager = new PagerEasyUI<UserDTO>();
		// 2、获取用户easyUI数据
		List<User> users = userDao.findByEasyUI(hql.toString(), page, rows);
		// 3、转换用户数据
		List<UserDTO> userDTOS = new ArrayList<UserDTO>();
		for (User u : users) {
			/**
			 * String groupIds = ""; String groupNames = ""; String roleIds =
			 * ""; String roleNames = ""; UserDTO userDTO = new UserDTO(u);
			 * List<UserGroup> userGroups =
			 * userGroupDao.listUserGroups(u.getId()); for (UserGroup userGroup
			 * : userGroups) { groupIds += userGroup.getGroupId() + ",";
			 * groupNames += userGroup.getGroupName() + ","; } //
			 * 根据用户ID获取用户对应的角色信息 List<UserRole> userRoles =
			 * userRoleDao.listUserRoles(u.getId()); for (UserRole userRole :
			 * userRoles) { roleIds += userRole.getRoleId() + ","; roleNames +=
			 * userRole.getRoleName() + ","; } if
			 * (EmptyUtil.isNotEmpty(groupIds)) { groupIds =
			 * groupIds.substring(0, groupIds.length() - 1); } if
			 * (EmptyUtil.isNotEmpty(groupNames)) { groupNames =
			 * groupNames.substring(0, groupNames.length() - 1); } if
			 * (EmptyUtil.isNotEmpty(roleIds)) { roleIds = roleIds.substring(0,
			 * roleIds.length() - 1); } if (EmptyUtil.isNotEmpty(roleNames)) {
			 * roleNames = roleNames.substring(0, roleNames.length() - 1); }
			 * userDTO.setGroupIds(groupIds); userDTO.setGroupNames(groupNames);
			 * userDTO.setRoleIds(roleIds); userDTO.setRoleNames(roleNames);
			 */
			userDTOS.add(new UserDTO(u));
		}
		easyUIPager.setRows(userDTOS);
		easyUIPager.setTotal((Long) userDao.queryByHql(" select count(*) " + hql.substring(0, hql.indexOf("order by"))));
		return easyUIPager;
	}

	@Override
	public AjaxObj updatePwd(User user, String password, String passwordNew, String passwordRe) throws Exception {
		if (user == null) {
			return new AjaxObj(0, "获取用户信息失败，请稍后再试！");
		}
		if (password == null || "".equals(password.trim())) {
			return new AjaxObj(0, "原密码不能为空！");
		}
		if (passwordNew == null || "".equals(passwordNew.trim())) {
			return new AjaxObj(0, "新密码不能为空！");
		}
		if (!passwordNew.equals(passwordRe)) {
			return new AjaxObj(0, "两次密码不一致");
		}
		if (!user.getPassword().equals(Md5Util.md5(user.getUsername(), password))) {
			return new AjaxObj(0, "原密码输入不正确！");
		}
		user.setPassword(Md5Util.md5(user.getUsername(), passwordNew));
		userDao.update(user);
		return new AjaxObj(1, "密码更新成功，请牢记新密码！", passwordNew);
	}

	@Override
	public AjaxObj updateAllPwd(String ids, String names) throws Exception {
		String hql = " update User u set u.password=? where u.id = ? ";
		if (EmptyUtil.isNotEmpty(ids)) {
			String[] idss = ids.split(",");
			String[] namess = names.split(",");
			if (idss != null && idss.length > 0) {
				for (int i = 0; i < idss.length; i++) {
					userDao.executeByHql(hql, new Object[] { Md5Util.md5(namess[i], "123"), Long.parseLong(idss[i]) });
				}
				return new AjaxObj(1, "密码重置成功！");
			}
		} else {
			return new AjaxObj(0, "请选择要重置密码的记录！");
		}
		return new AjaxObj(0, "重置密码失败！");
	}

	@Override
	public AjaxObj updateUserStart(String ids, String names) throws Exception {
		String hql = "update User u set u.status=1 where u.id=?";
		if (EmptyUtil.isNotEmpty(ids)) {
			String[] idss = ids.split(",");
			if (idss != null && idss.length > 0) {
				for (int i = 0; i < idss.length; i++) {
					userDao.executeByHql(hql, Long.valueOf(idss[i]));
				}
				return new AjaxObj(1, "开启使用成功！");
			}
		} else {
			return new AjaxObj(0, "请选择要开启的记录！");
		}
		return new AjaxObj(0, "开启使用失败！");
	}

	@Override
	public AjaxObj updateUserStop(String ids, String names) throws Exception {
		String hql = "update User u set u.status=-1 where u.id=?";
		if (EmptyUtil.isNotEmpty(ids)) {
			String[] idss = ids.split(",");
			if (idss != null && idss.length > 0) {
				for (int i = 0; i < idss.length; i++) {
					userDao.executeByHql(hql, Long.valueOf(idss[i]));
				}
				return new AjaxObj(1, "禁用成功！");
			}
		} else {
			return new AjaxObj(0, "请选择要禁用的记录！");
		}
		return new AjaxObj(0, "禁用失败！");
	}

	@Override
	public List<UserRole> listUserRoles(long userId) throws Exception {
		return userRoleDao.listUserRoles(userId);
	}

	@Override
	public List<User> listGroupUsers(long groupId) {
		List<UserGroup> userGroups = userGroupDao.listGroupUsers(groupId);
		List<User> users = new ArrayList<User>();
		for (UserGroup userGroup : userGroups) {
			users.add(userDao.load(userGroup.getUserId()));
		}
		return users;
	}

	@Override
	public List<User> list(String ids) throws Exception {
		String hql = " from User u where u.id in(" + ids + ")";
		return userDao.list(hql);
	}

	@Override
	public User load(long id) throws Exception {
		return userDao.load(id);
	}

	@Override
	public User loadByUserName(String username) {
		return userDao.loadByUsername(username);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public Set<String> findRoles(String username) {
		return userRoleDao.findRoles(username);
	}

	@Override
	public Set<String> findPermissions(String username) {
		return null;
	}

	@Override
	public AjaxObj verify(String fieldVlaue) {
		User user = userDao.loadByUsername(fieldVlaue);
		if (user == null) {
			return new AjaxObj(1, "当前用户名可使用");
		} else {
			return new AjaxObj(0, "当前用户已存在");

		}
	}
}